// ~ CopyRight © 2012 USTC SINOVATE  SOFTWARE CO.LTD All Rights Reserved.

package com.jck.data.util;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.jck.data.server.StartDataServer;
/*
 * 邮箱发送辅助类
 * @author jacking.jiao
 * @date 2016.4.11
 */
public class MailUtil {
	/**
	 * 邮箱登录名称
	 */
	private String mailUseName;
	/**
	 * 邮箱登录密码
	 */
	private String mailPassWord;
	/**
	 * smtp发送协议地址
	 */
	private String smtpServerHost;
	/**
	 * smtp发送协议端口，默认25
	 */
	private String smtpServerPort="25";
	 
    private MimeMessage message;
    private Session session;
    private Transport transport;
    
    Properties props = new Properties();

	/**
	 * 构建发送者的相关必要信息
	 * @param mailUseName 邮箱登录名称
	 * @param mailPassWord 邮箱登录密码
	 * @param smtpServerHost smtp发送协议地址
	 * @param smtpServerPort smtp发送协议端口，默认25
	 */
	public MailUtil(String mailUseName, String mailPassWord,
			String smtpServerHost, String smtpServerPort) {
		super();
		this.mailUseName = mailUseName;
		this.mailPassWord = mailPassWord;
		this.smtpServerHost = smtpServerHost;
		this.smtpServerPort = smtpServerPort;
		
	  props.setProperty("mail.smtp.host", this.smtpServerHost);
	  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	  props.setProperty("mail.smtp.socketFactory.fallback", "false");
	  props.setProperty("mail.smtp.port", this.smtpServerPort);
	  props.setProperty("mail.smtp.socketFactory.port",this.smtpServerPort );
	  props.put("mail.smtp.auth", "true");
	    session = Session.getInstance(props);
//        session.setDebug(true);// 开启后有调试信息
        message = new MimeMessage(session);
		
	}
	/**
	 * 构建发送者的相关必要信息
	 * @param mailUseName 邮箱登录名称
	 * @param mailPassWord 邮箱登录密码
	 * @param smtpServerHost smtp发送协议地址
	 */
	public MailUtil(String mailUseName, String mailPassWord,
			String smtpServerHost) {
		super();
		this.mailUseName = mailUseName;
		this.mailPassWord = mailPassWord;
		this.smtpServerHost = smtpServerHost;
		
		props.put("mail.smtp.host", smtpServerHost);
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.auth", "true");
	    session = Session.getInstance(props);
//        session.setDebug(true);// 开启后有调试信息
        message = new MimeMessage(session);
	
	}
	
	/**
	 * 发送电子邮件
	 * 
	 * @param receiver
	 *            邮件接收者
	 * @param title
	 *            邮件的标题
	 * @param content
	 *            邮件的内容
	 * @param sender
	 *            邮件发送者
	 * @throws MessagingException 
	 */
	public  void sendEmail( String receiver,String title, String content, String sender) throws MessagingException
			 {
		Properties props = new Properties();
		props.put("mail.host", smtpServerHost);
		props.put("mail.transport.protocol", "smtp");
		// props.put("mail.smtp.host",smtpHost);//发信的主机，这里要把您的域名的SMTP指向正确的邮件服务器上，这里一般不要动！
		props.put("mail.smtp.auth", "true");
		Session s = Session.getDefaultInstance(props);
//		s.setDebug(true);
		MimeMessage message = new MimeMessage(s);
		// 给消息对象设置发件人/收件人/主题/发信时间
		// 发件人的邮箱
		InternetAddress from = new InternetAddress(sender);
		message.setFrom(from);
		InternetAddress to = new InternetAddress(receiver);
		message.setRecipient(Message.RecipientType.TO, to);
		message.setSubject(title);
		message.setSentDate(new Date());
		// 给消息对象设置内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf-8");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		message.saveChanges();
		Transport transport = s.getTransport("smtp");
		transport.connect(smtpServerHost, this.mailUseName, this.mailPassWord);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}
	
	
	/**
	 * 发送电子邮件

	 * @param receiver
	 *            邮件接收者
	 * @param title
	 *            邮件的标题
	 * @param content
	 *            邮件的内容
	 * @param sender
	 *            邮件发送者
	 * @throws MessagingException 
	 */
	public  void sendEmailSSL(String receiver,String title, String content, String sender) throws MessagingException
			 {
		  Properties props = System.getProperties();
		  props.setProperty("mail.smtp.host", this.smtpServerHost);
		  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		  props.setProperty("mail.smtp.socketFactory.fallback", "false");
		  props.setProperty("mail.smtp.port", this.smtpServerPort);
		  props.setProperty("mail.smtp.socketFactory.port",this.smtpServerPort );
		  props.put("mail.smtp.auth", "true");
		Session s = Session.getDefaultInstance(props);
//		s.setDebug(true);
		MimeMessage message = new MimeMessage(s);
		// 给消息对象设置发件人/收件人/主题/发信时间
		// 发件人的邮箱
		InternetAddress from = new InternetAddress(sender);
		message.setFrom(from);
		InternetAddress to = new InternetAddress(receiver);
		message.setRecipient(Message.RecipientType.TO, to);
		message.setSubject(title);
		message.setSentDate(new Date());
		// 给消息对象设置内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf-8");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		message.saveChanges();
		Transport transport = s.getTransport("smtp");
		transport.connect(smtpServerHost, this.mailUseName, this.mailPassWord);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}


	/**
	 * 发送电子邮件
	 * @param receiver
	 *            邮件接收者 多人 “;”分割
	 * @param copy
	 *            抄送列表 多人 “;”分割
	 * @param title
	 *            邮件的标题
	 * @param content
	 *            邮件的内容
	 * @param sender
	 *            邮件发送者
	 * @param isSSL
	 *           是否SSL
	 * @throws Exception
	 */
	public  void sendCopyEmail(String receiver, String copy,String title, String content, String sender,boolean isSSL)
			throws Exception {
		
		
		if(isSSL){
			  props.setProperty("mail.smtp.host", this.smtpServerHost);
			  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			  props.setProperty("mail.smtp.socketFactory.fallback", "false");
			  props.setProperty("mail.smtp.port", this.smtpServerPort);
			  props.setProperty("mail.smtp.socketFactory.port",this.smtpServerPort );
			  props.put("mail.smtp.auth", "true");
			
		}else{
//			System.out.println("非ssl");
			props.setProperty("mail.smtp.host", this.smtpServerHost);
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.auth", "true");
		}
		Session s = Session.getDefaultInstance(props);
//		s.setDebug(true);
		MimeMessage message = new MimeMessage(s);
		// 给消息对象设置发件人/收件人/主题/发信时间
		// 发件人的邮箱
		InternetAddress from = new InternetAddress(sender);
		message.setFrom(from);
		String[] receivers = receiver.split(";");
		InternetAddress[] to = new InternetAddress[receivers.length];
		for (int i = 0; i < receivers.length; i++) {
			to[i] = new InternetAddress(receivers[i]);
		}
		message.setRecipients(Message.RecipientType.TO, to);

		String[] copys = copy.split(";");
		InternetAddress[] cc = new InternetAddress[copys.length];
		for (int i = 0; i < copys.length; i++) {
			cc[i] = new InternetAddress(copys[i]);
		}
		message.setRecipients(Message.RecipientType.CC, cc);

		message.setSubject(title);
		message.setSentDate(new Date());
		// 给消息对象设置内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf-8");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		message.saveChanges();
		Transport transport = s.getTransport("smtp");
		transport.connect(this.smtpServerHost, this.mailUseName, this.mailPassWord);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}
	
	public static void main(String[] args) {
		try {
//			System.setProperty("java.net.preferIPv4Stack", "true");  
//			MailUtil mu=new MailUtil("jiaojing119@163.com", "jiaojing119", "smtp.163.com", "465");
			MailUtil mu=new MailUtil("986851760@qq.com", "izagopxzkxzsbeca", "smtp.qq.com", "465");
//			mu.sendEmail("986851760@qq.com","986851760@qq.com", "标题", "我系统测试邮件","jiaojing119@163.com",false);
			
			mu.sendEmailSSL("986851760@qq.com", "我系统测试邮件", "你好，我是焦竞", "986851760@qq.com");
//			System.out.println("发成功");
		/*	 File attachment = new File("D:\\test.rar");
			 String receiver="jiaojing119@163.com";
		     mu.sendEmailwhithAtt(receiver, "我系统测试邮件", "你好，我是焦竞", "jiaojing119@163.com", attachment);*/
		 	System.out.println("发成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
 


		/**
		 * 
		 * @param receiver
		 * @param title
		 * @param content
		 * @param sender
		 * @param attachment
		 */
	    public void sendEmailwhithAtt( String receiver,String title, String content, String sender,File attachment) {
	    	  try {
	              // 发件人
	              InternetAddress from = new InternetAddress(sender);
	              message.setFrom(from);

	              // 收件人
	              InternetAddress to = new InternetAddress(receiver);
	              message.setRecipient(Message.RecipientType.TO, to);

	              // 邮件主题
	              message.setSubject(title);

	              // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
	              Multipart multipart = new MimeMultipart();
	              
	              // 添加邮件正文
	              BodyPart contentPart = new MimeBodyPart();
	              contentPart.setContent(content, "text/html;charset=UTF-8");
	              multipart.addBodyPart(contentPart);
	              
	              // 添加附件的内容
	              if (attachment != null) {
	                  BodyPart attachmentBodyPart = new MimeBodyPart();
	                  DataSource source = new FileDataSource(attachment);
	                  attachmentBodyPart.setDataHandler(new DataHandler(source));
	                  //MimeUtility.encodeWord可以避免文件名乱码
	                  attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
	                  multipart.addBodyPart(attachmentBodyPart);
	              }
	              
	              // 将multipart对象放到message中
	              message.setContent(multipart);
	              // 保存邮件
	              message.saveChanges();

	              transport = session.getTransport("smtp");
	              // smtp验证，就是你用来发邮件的邮箱用户名密码
	              transport.connect(this.smtpServerHost, this.mailUseName, this.mailPassWord);
	              // 发送
	              transport.sendMessage(message, message.getAllRecipients());

//	              System.out.println("send success!");
	          } catch (Exception e) {
	              e.printStackTrace();
	          } finally {
	              if (transport != null) {
	                  try {
	                      transport.close();
	                  } catch (MessagingException e) {
	                      e.printStackTrace();
	                  }
	              }
	          }
	    }
	    
	    /**
	     * 
	     * @param receiver 接收人
	     * @param title    标题
	     * @param content  正文内容 
	     * @param isSSL   是否ssl协议 
	     * @throws MessagingException 
	     */
	    public static void sendDefaultEmail(String receiver,String title, String content,boolean isSSL) {
	    	Properties property =StartDataServer.property;
	    	String mailUseName=property.getProperty("mailUseName");
	    	String mailPassWord=property.getProperty("mailPassWord");
	    	String smtpServerHost=property.getProperty("smtpServerHost");
	    	String smtpServerPort=property.getProperty("smtpServerPort");
	    	String preceiver=property.getProperty("receiver");
	    	MailUtil mu=new MailUtil(mailUseName, mailPassWord, smtpServerHost, smtpServerPort);
	    	receiver="".equals(receiver)||null==receiver?preceiver:receiver;
	    	try {
	    		if(isSSL){
	    			
					mu.sendEmailSSL(receiver, title, content, mailUseName);
			 
	    	}else{
	    		   mu.sendEmail(receiver, title, content, mailUseName);
	    	}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	
	    }
	    public static void sendDefaultEmailByAdmin(String title, String content,boolean isSSL) {
	    	Properties property =StartDataServer.property;
	    	String mailUseName=property.getProperty("mailUseName");
	    	String mailPassWord=property.getProperty("mailPassWord");
	    	String smtpServerHost=property.getProperty("smtpServerHost");
	    	String smtpServerPort=property.getProperty("smtpServerPort");
	    	String receiver=property.getProperty("receiver");
	    	MailUtil mu=new MailUtil(mailUseName, mailPassWord, smtpServerHost, smtpServerPort);
	    	try {
	    		if(isSSL){
	    			mu.sendEmailSSL(receiver, title, content, mailUseName);
	    		}else{
	    			mu.sendEmail(receiver, title, content, mailUseName);
	    		}
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	}
	    	
	    }


}
